package com.zhijian.medical.service.impl;


import com.zhijian.medical.config.Constants;
import com.zhijian.medical.dao.remote.RfidMapper;
import com.zhijian.medical.entity.vo.request.MedicalDeviceSearchVo;
import com.zhijian.medical.entity.vo.request.RfidSearchVo;
import com.zhijian.medical.entity.vo.response.MedicalDeviceVo;
import com.zhijian.medical.entity.vo.response.RfidVo;
import com.zhijian.medical.enums.ResponseCodeEnum;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.service.LocationService;
import com.zhijian.medical.service.MonitorService;
import com.zhijian.medical.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Service
public class MonitorServiceImpl implements MonitorService {


    @Autowired
    private RfidMapper rfidMapper;


    @Autowired
    private LocationService locationService;

    public Integer count(RfidSearchVo deviceSearchVo) {
        return rfidMapper.count(deviceSearchVo);
    }


    public List<RfidVo> selectList(RfidSearchVo deviceSearchVo) {

        List<RfidVo> deviceVos = rfidMapper.selectList(deviceSearchVo);
        if (!deviceVos.isEmpty()) {
            List<RfidVo> result = new LinkedList<>();
            try{
                deviceVos.forEach(vo -> {
                    vo.setAfterAddress(vo.getAfterAddress()!=null?locationService.concatNameByDeepId(Long.valueOf(vo.getAfterAddress())).toString():"");
//                result.add(vo);
                    vo.setBeforeAddress(vo.getBeforeAddress()!= null ?locationService.concatNameByDeepId(Long.valueOf(vo.getBeforeAddress())).toString():"");
                    result.add(vo);
                });
            }catch (Exception e){
                return result;
            }

            return result;
        }
        return deviceVos;
    }

    @Override
    public Page<RfidVo> selectByDetails(RfidSearchVo param) {

        if (param.getPageNum() < 1 || param.getPageSize() < 1) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "分页参数不合法");
        }
        if (null != param.getLocationId() && !Objects.equals(param.getLocationId(), Constants.Location.NO_LOCATION)) {
            //选择一个位置后，要选他所有的子级区域，除非是-1.-1代表没有分配位置
            param.setLocationIds(locationService.concatIdsByParentId(param.getLocationId()));
            param.setLocationId(null);
        }


        //先直接查总数
        int count = count(param);
        //分页
        Page<RfidVo> page = new Page<>(true, count, param.getPageNum(), param.getPageSize());
        param.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<RfidVo> responseVos = this.selectList(param);
        page.setData(responseVos);
        return page;
    }
}
